package com.louis.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

public final class ResourceBundleUtil {

	private final static Logger logger = Logger
			.getLogger(ResourceBundleUtil.class);

	private static Map<String, ResourceBundle> resourceBundles = new HashMap<String, ResourceBundle>();

	public static ResourceBundle getResourceBundle(String baseName) {
		ResourceBundle bundle = resourceBundles.get(baseName);
		if (bundle == null) {
			try {
				bundle = ResourceBundle.getBundle(baseName);
			} catch (Exception e) {
				logger.warn(e.getMessage());
			}
			if (bundle != null) {
				resourceBundles.put(baseName, bundle);
			}
		}
		return bundle;
	}

	public static String[] getArray(String baseName, String key) {
		String[] array = null;
		ResourceBundle bundle = getResourceBundle(baseName);
		if (bundle != null) {
			try {
				String value = bundle.getString(key);
				if (StringUtil.hasText(value)) {
					array = value.split(",");
				}
			} catch (Exception e) {
				logger.warn(e.getMessage());
			}

		}
		return array;
	}

	public static List<String> getList(String baseName, String key) {
		List<String> list = new ArrayList<String>();
		String[] array = getArray(baseName, key);
		if (array != null) {
			for (String value : array) {
				list.add(value);
			}
		}
		return list;
	}

	public static String getString(String baseName, String key) {
		return getString(baseName, key, null);
	}

	public static String getString(String baseName, String key,
			String defaultValue) {
		String value = defaultValue;
		ResourceBundle bundle = getResourceBundle(baseName);
		if (bundle != null) {
			try {
				value = bundle.getString(key);
			} catch (Exception e) {
				logger.warn(e.getMessage());
			}
		}
		return value;
	}

	public static boolean getBoolean(String baseName, String key) {
		return getBoolean(baseName, key, false);
	}

	public static Map<String, String> getMap(String baseName, String key) {
		Map<String, String> map = new HashMap<String, String>();
		String string = getString(baseName, key);
		if (StringUtil.hasText(string)) {
			String[] value = string.split(",");
			if (ArrayUtil.hasArray(value)) {
				for (String string2 : value) {
					String[] split = string2.split("=");
					if (ArrayUtil.hasArray(split) && split.length == 2) {
						map.put(split[0], split[1]);
					}
				}
			}
		}
		return map;
	}

	public static boolean getBoolean(String baseName, String key,
			boolean defaultValue) {
		boolean flag = defaultValue;
		ResourceBundle bundle = getResourceBundle(baseName);
		if (bundle != null) {
			try {
				String value = bundle.getString(key);
				flag = DataTypeConverterUtil.parseBoolean(value, defaultValue);
			} catch (Exception e) {
				logger.warn(e.getMessage());
			}
		}
		return flag;
	}

}
